package com.autonavi.abs.common.util;

import com.autonavi.abs.common.constant.RegexConstant;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

/**
 * @author wwy
 * @version V1.0
 * <p>http请求参数处理</p>
 * @date 2020-07-20 15:55
 */
public class RequestParamUtils {

    /**
     * 解析url中的参数至map中
     * 如:?name=xx&age=yy=zz，解析为 name:xx;age:yy=zz
     *
     * @param queryString
     * @return
     */
    public static Map<String, String> getParamMap(String queryString) {

        Map<String, String> paramMap = new HashMap<>();
        if (StringUtils.isBlank(queryString)) {
            throw new RuntimeException("请求参数为空");
        }

        if (queryString.startsWith(RegexConstant.EN_QUESTION_MARK)) {
            queryString = queryString.substring(1);
        }

        String[] paramArray = queryString.split(RegexConstant.AND_MARK);
        if (ArrayUtils.isEmpty(paramArray)) {
            throw new RuntimeException("请求参数为空");
        }

        Stream.of(paramArray).filter((item) -> StringUtils.isNotBlank(item)).forEach((item) -> {

            String[] fieldArray = item.split(RegexConstant.EQUAL_MARK);
            if (ArrayUtils.isEmpty(fieldArray)) {
                return;
            }

            //解决value中还有=的问题
            String value = fieldArray.length == 2 ? fieldArray[1]
                    : String.join(RegexConstant.EQUAL_MARK, ArrayUtils.remove(fieldArray, 0));

            paramMap.put(fieldArray[0], value);

        });

        return paramMap;

    }

    /**
     * cifa转换为map
     *
     * @param cifa
     * @return
     */
    public static Map<String, String> getCifaMap(String cifa) {

        Map<String, String> cifaMap = Maps.newHashMap();
        if (StringUtils.isBlank(cifa)) {
            return cifaMap;
        }

        String[] kvArray = cifa.split("\\;");
        Stream.of(kvArray).forEach((kvStr) -> {

            if (StringUtils.isBlank(kvStr)) {
                return;
            }
            String[] kv = kvStr.split("\\=");
            if (kv == null) {
                return;
            }
            if (kv.length == 1) {
                cifaMap.put(kv[0], null);
            } else if (kv.length == 2) {
                cifaMap.put(kv[0], kv[1]);
            }
        });

        return cifaMap;

    }

}
